import 'package:flutter/widgets.dart';
import 'package:library_base/entities/enum_entity.dart';

extension ListExt<E> on List<E> {
  ///循环回调下标和实体类的循环,原生的forEach不带下标
  forEachIndexed(Function(int, E) eachCallback) {
    for (int i = 0; i < length; i++) {
      eachCallback(i, this[i]);
    }
  }

  ///不按排序校对两个集合的长度和内容,如果是对象则需要重写hashCode和operator，参考GoodsChildEntity
  bool equal(List<E> otherList) {
    if (length != otherList.length) {
      return false;
    } else {
      for (int netInt = 0; netInt < length; netInt++) {
        ///这里不知道为什么要加this否则读取不了具体的实体类
        var netElement = this[netInt];
        bool isInclude = false;
        for (int localInt = 0; localInt < length; localInt++) {
          var localElement = otherList[localInt];
          if (netElement == localElement) {
            isInclude = true;
            break;
          }
        }
        if (!isInclude) {
          return false;
        }
      }
    }
    return true;
  }

  List<Widget> buildItem(
    Widget Function(int, E) itemWidget, {
    Widget Function()? dividingLine,
    DivideType divideType = DivideType.ALL,
  }) {
    var widgets = <Widget>[];
    forEachIndexed((index, element) {
      if (index == 0 && index == (length - 1)) {
        if (dividingLine != null &&
            (divideType == DivideType.ALL || divideType == DivideType.MIDDLE_WITH_TOP)) {
          widgets.add(dividingLine.call());
        }
        widgets.add(itemWidget.call(index, element));
        if (dividingLine != null &&
            (divideType == DivideType.ALL || divideType == DivideType.MIDDLE_WITH_BOTTOM )) {
          widgets.add(dividingLine.call());
        }
      } else {
        if (index == 0) {
          if (dividingLine != null &&
              (divideType == DivideType.ALL || divideType == DivideType.MIDDLE_WITH_TOP)) {
            widgets.add(dividingLine.call());
          }
          widgets.add(itemWidget.call(index, element));
          if (dividingLine != null &&
              (divideType == DivideType.ALL || divideType == DivideType.MIDDLE_WITH_BOTTOM || divideType == DivideType.MIDDLE)) {
            widgets.add(dividingLine.call());
          }
        } else if (index == (length - 1)) {
          widgets.add(itemWidget.call(index, element));
          if (dividingLine != null &&
              (divideType == DivideType.ALL || divideType == DivideType.MIDDLE_WITH_BOTTOM)) {
            widgets.add(dividingLine.call());
          }
        } else {
          widgets.add(itemWidget.call(index, element));
          if (dividingLine != null &&
              (divideType == DivideType.ALL || divideType == DivideType.MIDDLE_WITH_BOTTOM || divideType == DivideType.MIDDLE)) {
            widgets.add(dividingLine.call());
          }
        }
      }
    });
    return widgets;
  }
}
